package com.example.mybrowser;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.example.mybrowser.WebsiteInfo.Information;

public class SubService extends Thread{
	
	private WebView SubWebView;
	
	static private String[] LinkList = new String[2000];
	static private int LinkSize = 0;
	static public Map<String, Integer> urlList = new HashMap<String, Integer>();
	
	//SubActivity activity = new SubActivity();
	SubActivity activity;
	
	public SubService(SubActivity activity){
        this.activity = activity;
	}
	 
	private class SubServiceJSInterface
	{  
		@JavascriptInterface 
		public void processHTMLandURL(String url, String html) {
		}
		
	    @JavascriptInterface 
	    public void processHTML(String html)  
	    {
	    	Log.i("HTML", html);
	    	String[] NewLinkList = new SubService(activity).parseHTML(html);
	    	if (SubActivity.SubLinkFlag){
	    		Log.i("processHTML","NewLinkList.length "+NewLinkList.length);
		    	/*for (int i = 0;i < NewLinkList.length;i ++){
		    		Log.i("processHTML","i "+i);
		    		if (NewLinkList[i] != null){
		    			//if(NewLinkList[i].length() > 7 && NewLinkList[i].substring(0, 7) == "http://"){
			    		if (NewLinkList[i].indexOf("http://") != -1){
		    				SubActivity.LinkList[SubActivity.LinkListNum] = NewLinkList[i];
			    			SubActivity.LinkListNum ++;
			    			Log.i("SubActivity.LinkListNum","SubActivity.LinkListNum "+SubActivity.LinkListNum);
		    			}
		    		}
		    		else 
		    			break;
		    	}*/
	    		/*Iterator iter = urlList.entrySet().iterator();
        		int num = SubService.urlList.size();
        		Log.v("urlnum", String.valueOf(num));
        		while (iter.hasNext()) { 
        		    Map.Entry entry = (Map.Entry) iter.next(); 
        		    Object key = (String)entry.getKey(); 
        		    Log.v("urls", (String)key);
        		    SubActivity.LinkList[SubActivity.LinkListNum] = (String) key;
	    			SubActivity.LinkListNum ++;
	    			//Log.v("urlnum", String.valueOf(SubActivity.LinkListNum));
        		} 
        		Log.v("urlnumlink", String.valueOf(SubActivity.LinkListNum));*/
	    	}
	    	Log.d("HTML", "------      ------");
	    	activity.getDataHandler.sendEmptyMessage(0);
	    	
	    }
	    
	    @JavascriptInterface
	    public void getURL(String url)
	    {
	    	url = url.substring(6, url.length() - 7);
	    	Log.i("URL", url);
	    }
	    
	    @JavascriptInterface 
	    public void showHTML(String html)  
	    {
	    	Log.i("HTML", html.split("\n")[0]);
	    }
	}
	
	public boolean SubStart(String URL) {
		// Fetch SubList
		/*
		Map<Integer, Information> SubListMap = WebsiteInfo.RSSInfo;
		Iterator<Entry<Integer, Information>> SubIter = SubListMap.entrySet().iterator();
		*/
		
		/*
		while (SubIter.hasNext()) {
			Entry<Integer, Information> entry = SubIter.next(); 
			SubList[SubListCount] = entry.getValue().URL.toString();
			SubListCount ++;
		}
		*/
			SubWebView = MainActivity.subview;
			SubWebView.setVisibility(View.INVISIBLE);
			SubWebView.getSettings().setJavaScriptEnabled(true);  
			SubWebView.addJavascriptInterface(new SubServiceJSInterface(), "HTMLOUT");  
			SubWebView.setWebViewClient(new WebViewClient() {  
			    @Override  
			    public void onPageFinished(WebView view, String url)  
			    {  
			    	//SubListCount --;
			    	Log.i("WebView", "onPageFinished");
			    	
			        /* This call inject JavaScript into the page which just finished loading. */  
			    	SubWebView.loadUrl("javascript:window.HTMLOUT.processHTML("
			    			+ "'<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");  
			    }
			});  
			SubWebView.loadUrl(URL);	
			Log.i("SubService", "Sync done.");
		
			return false;
	}

	public String[] parseHTML(String html)
	{
		//String[] SubWeb = new String[2000];
		/*Document doc = Jsoup.parse(html);
		Elements alinks = doc.select("a[href]");
		//Elements llinks = doc.select("link[href]");
		int i = 0;
		for(Element link : alinks){
			SubWeb[i] = link.attr("href");
			Log.i("ParseHTML "+i, SubWeb[i]);
			i ++;
		}
		Elements llinks = doc.select("link[href]");
		for(Element link : llinks){
			SubWeb[i] = link.attr("href");
			Log.i("ParseHTML "+i, SubWeb[i]);
			i ++;
		}
		Log.i("ParseHTML", "------");*/
		String[] SubWeb = html.split("a href=\"");
		for(String url : SubWeb)
		{
			if (url.startsWith("http"))
			{
				int index = url.indexOf("\"");
				if (index > 0)
				{
					url = url.substring(0, index);
				}
				//Log.v("url", url);
				//urlList.put(url, 1);
				SubActivity.LinkList[SubActivity.LinkListNum] = url;
				Log.v("url" + String.valueOf(SubActivity.LinkListNum), url);
    			SubActivity.LinkListNum ++;
				
			}
			else if (url.startsWith("/"))
			{
				int index = url.indexOf("\"");
				if (index > 0){
					url = "http://m.sohu.com" + url.substring(0, index);
				}
				//Log.v("url", url);
				//urlList.put(url, 1);
				SubActivity.LinkList[SubActivity.LinkListNum] = url;
				Log.v("url" + String.valueOf(SubActivity.LinkListNum), url);
    			SubActivity.LinkListNum ++;
			}
		}
		int num = urlList.size();
		System.out.println("num:" + num);
		return SubWeb;
	}
	
	/*
	public void Load(int i){
		Flag = true;
		Log.i("Load", "this is "+i);
		SubWebView.loadUrl(SubList[i-1]);
	}
	*/
}
